/*用户中心*/
import React, { useEffect, useMemo, useRef, useState } from "react"
import {
    Avatar,
    BreadcrumbItem,
    Breadcrumbs,
    Button,
    Card,
    CardHeader,
    Chip,
    Code,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    DropdownTrigger,
    Image,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Spinner,
    Switch,
    Table,
    TableBody,
    TableCell,
    TableColumn,
    TableHeader,
    TableRow,
    useDisclosure,
    Tooltip
} from "@nextui-org/react"
import FolderService from "@/app/service/folderService"
import NoteService from "@/app/service/noteService"
import { useAsyncList } from "@react-stately/data"
import { AiFillHome, AiOutlineAppstore, AiOutlineBars } from "react-icons/ai"
import { CardBody, CardFooter } from "@nextui-org/card"
import { BiDotsVerticalRounded, BiFolderOpen, BiPlus, BiEdit, BiAddToQueue, BiChevronLeft, BiChevronRight, BiChevronDown, BiHomeAlt, BiX } from "react-icons/bi"
import { useLocation, useSearchParams } from "react-router-dom"
import ToastUtil from "@/app/utils/toastUtil"
import CreateFolder from "@/app/components/profile/folder/createFolder"
import { delay } from "framer-motion"
import DelNoteService from "@/app/service/components/delNoteService"
import DelFolderService from "@/app/service/components/delFolderService"
import { cancelShare, createShare } from "@/app/service/shareService.tsx"
import { List } from "postcss/lib/list";
import { Emoji } from "@lezer/markdown";
import { DeleteIcon } from "@nextui-org/shared-icons";
import { Cookie } from "next/dist/compiled/@next/font/dist/google";
import { cookies } from "next/headers";
import cookie from "react-cookies";
import { inFifteenMinutes } from "@/app/constants/authTokenConstants";
import { any, number } from "prop-types";
import FindNoteService from "@/app/service/FindNoteService";
import { decodeFromBase64 } from "next/dist/build/webpack/loaders/utils";
import ExitLogin from "@/app/components/profile/exitLogin";
import SettingPage from "@/app/components/profile/SettingPage";
import UpdateFolder from "@/app/components/profile/folder/updateFolder"
import { useRouter } from "next/navigation";
import NoteListActions from "@/app/components/profile/note/note-list-actions";
import NoteShareModal from "@/app/components/share/NoteShareModal";
import DirectoryTree from "@/app/components/profile/DirectoryTree";

/**
 * 个人中心文件夹列表和笔记列表渲染页
 * @param searchKey
 * @param inSearch
 * @param setInSearch
 * @constructor
 */
export default function Profile({ searchKey, inSearch, setInSearch }: any) {
    //第一种方式 ---> 会更新当前状态 所以不能返回上一个状态
    // const [path, setPath] = useState(params.path);
    /**第二种方式 ---> 会更新URL参数 可以返回上一个状态*/
    const [search, setSearch] = useSearchParams()
    /**存储路由*/
    const [path, setPath] = useState(["/"])
    /**是否已加载状态定义*/
    const location = useLocation()
    const [isLoadingFolder, setIsLoadingFolder] = useState(true)
    const [isLoadingNote, setIsLoadingNote] = useState(true)
    const { isOpen, onOpen, onClose, onOpenChange } = useDisclosure()
    /**创建文件夹Modal状态*/
    const { isOpen: isOpenFolder, onOpen: onOpenFolder, onOpenChange: onOpenChangeFolder } = useDisclosure()
    /**创建笔记Modal状态*/
    const { isOpen: isOpenNote, onOpen: onOpenNote, onOpenChange: onOpenChangeNote } = useDisclosure()
    /**确认删除Modal状态*/
    const { isOpen: isOpenDelNote, onOpen: onOpenDelNote, onOpenChange: onOpenChangeDelNote } = useDisclosure()
    /**v确认删除Modal状态*/
    const { isOpen: isOpenDelFolder, onOpen: onOpenDelFolder, onOpenChange: onOpenChangeDelFolder } = useDisclosure()
    /**笔记Id临存*/
    const [noteId, setNoteId] = useState("")
    /**删除的笔记id和title*/
    const [delData, setDelData] = useState("")
    /**笔记排列方式*/
    const [noteIfGrid, setNoteIfGrid] = useState(cookie.load('noteIfGrid') == undefined ? 'false' : cookie.load('noteIfGrid'))
    /**目录排列方式*/
    const [folderIfGrid, setFolderIfGrid] = useState(cookie.load('folderIfGrid') == undefined ? 'false' : cookie.load('folderIfGrid'))
    /** 防止第一次重复请求 */
    const [enable, setEnable] = useState(false);
    /** 分页相关状态 */
    const [folderCurrent, setFolderCurrent] = useState(1);
    const [folderTotal, setFolderTotal] = useState(0);
    const [noteCurrent, setNoteCurrent] = useState(1);
    const [noteTotal, setNoteTotal] = useState(0);
    const pageSize = 100; // 每页显示100条
    /**修改文件夹Modal状态*/
    const { isOpen: isOpenUpdateFolder, onOpen: onOpenUpdateFolder, onOpenChange: onOpenChangeUpdateFolder } = useDisclosure()
    /**待修改的文件夹ID*/
    const [updateFolderId, setUpdateFolderId] = useState("")
    const router = useRouter()
    /**分享笔记模态框状态*/
    const [isOpenNoteShare, setIsOpenNoteShare] = useState(false);
    const [shareNoteId, setShareNoteId] = useState<number | null>(null);
    /**文件夹名称缓存，保存ID到名称的映射*/
    const [folderNameMap, setFolderNameMap] = useState<{ [key: string]: string }>({});
    /**是否显示目录树*/
    const [showDirectoryTree, setShowDirectoryTree] = useState<boolean>(true);
    /**目录树宽度 */
    const [directoryTreeWidth, setDirectoryTreeWidth] = useState<number>(() => {
        // 尝试从localStorage读取用户保存的宽度，默认为256px (16rem)
        if (typeof window !== 'undefined') {
            const savedWidth = localStorage.getItem('directoryTreeWidth');
            return savedWidth ? parseInt(savedWidth) : 256;
        }
        return 256;
    });
    const MIN_TREE_WIDTH = 180; // 最小宽度
    const MAX_TREE_WIDTH = 500; // 最大宽度
    const [isResizing, setIsResizing] = useState<boolean>(false);

    /**获取文件夹数据*/
    let listFolder = useAsyncList({
        async load({ signal }) {
            const path = search.get("path")
            setIsLoadingFolder(true);
            const folderData = await FolderService(path === null ? "root" : path, folderCurrent, pageSize)
            setEnable(true)//结束Enable（防止重复请求）
            setIsLoadingFolder(false);
            if (folderData !== undefined && folderData !== null && folderData.status) {
                setFolderTotal(folderData.data.total || 0);

                // 保存文件夹名称和ID的映射关系，用于面包屑导航
                if (folderData.data.records) {
                    const newFolderMap: { [key: string]: string } = {};
                    folderData.data.records.forEach((folder: any) => {
                        newFolderMap[folder.id] = folder.name;
                    });

                    // 如果有当前文件夹信息，也添加到映射
                    if (folderData.data.currentFolder && path && path !== "root") {
                        newFolderMap[path] = folderData.data.currentFolder.name;

                        // 保存到本地存储，以便在页面刷新或返回时仍能访问
                        try {
                            // 获取现有映射
                            const savedMap = localStorage.getItem('folderNameMap');
                            const existingMap = savedMap ? JSON.parse(savedMap) : {};
                            // 合并新的映射
                            const updatedMap = { ...existingMap, ...newFolderMap };
                            // 保存回本地存储
                            localStorage.setItem('folderNameMap', JSON.stringify(updatedMap));
                        } catch (e) {
                            console.error('保存文件夹映射失败:', e);
                        }
                    }

                    // 合并到已有的映射中
                    setFolderNameMap(prev => ({
                        ...prev,
                        ...newFolderMap
                    }));
                }

                return {
                    items: folderData.data.records || []
                }
            } else {
                return {
                    items: []
                }
            }
        }
    })

    /**获取笔记数据*/
    let listNote = useAsyncList({
        async load({ signal }) {
            setInSearch(false);
            const path = search.get("path")
            setIsLoadingNote(true);
            const noteData = await NoteService(path === null ? "root" : path, noteCurrent, pageSize)
            setEnable(true)//结束Enable（防止重复请求）
            setIsLoadingNote(false);
            console.log("Profile组件获取笔记数据:", noteData);
            if (noteData !== undefined && noteData !== null && noteData.status) {
                setNoteTotal(noteData.data.total || 0);
                return {
                    items: noteData.data.records || []
                }
            } else {
                return {
                    items: []
                }
            }
        }
    })
    /**搜索笔记*/
    let findNote = useAsyncList({
        async load({ signal }) {
            // if (searchKey != '' && searchKey != undefined) {
            //     const findData = await FindNoteService(searchKey);
            //     if (findData !== undefined && findData !== null && findData.status) {
            //         setInSearch(true)
            //         ToastUtil(findData?.message, '🤪', 'success')
            //         return { items: findData.data }
            //     } else {
            //         ToastUtil(findData?.message, '🤨', 'warning')
            //         return {
            //             items: []
            //         }
            //     }
            // }
            return {
                items: []
            }
        }
    })

    /**订阅消息，接受消息时进行列表渲染*/
    PubSub.unsubscribe('keyword');
    PubSub.subscribe('keyword', (_, data) => {
        if (data == '' || data == undefined) {
            listNote.reload();
        } else {
            findNote.reload();
        }
    });
    /**创建一个消息监听器，列表发生变化重新渲染.*/
    //文件夹
    PubSub.unsubscribe("refreshFolder")
    PubSub.subscribe("refreshFolder", (_, data) => {
        listFolder.reload()//重新加载
    })
    //笔记
    PubSub.unsubscribe("refreshNote")
    PubSub.subscribe("refreshNote", (_, data) => {
        listNote.reload()
    })


    /**检测location地址更新状态的Hook钩子（就是自动执行的监听器）*/
    useEffect(() => {
        setIsLoadingNote(true)
        setIsLoadingFolder(true)
        // 重置分页
        setFolderCurrent(1);
        setNoteCurrent(1);

        async function fetchData() {
            /*更新路由栏路径*/
            const localUrl = search.get("path")
            if (localUrl === null || localUrl === "root" || localUrl === "/") {
                setPath(["/"])
            } else {
                // 尝试从已有的映射中获取文件夹名称
                const folderName = folderNameMap[localUrl] || localUrl;

                // 如果没有名称，尝试获取文件夹信息
                if (folderName === localUrl && localUrl) {
                    try {
                        const folderData = await FolderService(localUrl, 1, 1);
                        if (folderData && folderData.status && folderData.data.currentFolder) {
                            const currentFolder = folderData.data.currentFolder;
                            setFolderNameMap(prev => ({
                                ...prev,
                                [localUrl]: currentFolder.name
                            }));
                        }
                    } catch (error) {
                        console.error("获取文件夹信息失败:", error);
                    }
                }

                const newPathList = [...path] //复制当前路径列表
                //查找新路径在当前路径列表中的位置
                const index = newPathList.indexOf(localUrl)
                if (index !== -1) {
                    // 如果存在，则删除该路径后面的所有值
                    newPathList.splice(index + 1, newPathList.length - index - 1)
                } else {
                    //如果不存在，则将新路径合并到当前路径列表中
                    newPathList.push(...getPathParts(localUrl))
                }
                /*更新路由*/
                setPath(newPathList)
            }
            //在path或location变化时重新加载数据  路径发生了变化
            if (enable) {
                listFolder.reload()
                listNote.reload()
            }
            //更新加载中状态
            delay(() => {
                setIsLoadingFolder(false)
                setIsLoadingNote(false)
            }, 100)
        }

        fetchData().then(r => {
            /*执行fetchData时出错才执行*/
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [location])

    // 监听分页变化
    useEffect(() => {
        if (enable) {
            listFolder.reload();
        }
    }, [folderCurrent]);

    useEffect(() => {
        if (enable) {
            listNote.reload();
        }
    }, [noteCurrent]);

    // 在组件挂载时加载保存的映射
    useEffect(() => {
        try {
            const savedMap = localStorage.getItem('folderNameMap');
            if (savedMap) {
                const parsedMap = JSON.parse(savedMap);
                setFolderNameMap(prev => ({
                    ...prev,
                    ...parsedMap
                }));
            }
        } catch (e) {
            console.error('读取文件夹映射失败:', e);
        }
    }, []);

    /**选择目录时处理函数*/
    const handleSelectDirectory = (directoryId: string | null) => {
        if (directoryId === null) {
            setPath(["/"])
            setSearch("")
        } else {
            setSearch(`path=${directoryId}`)
        }
        setIsLoadingNote(true)
        setIsLoadingFolder(true)
    }

    /**处理调整宽度的逻辑 */
    const handleMouseDown = (e: React.MouseEvent) => {
        e.preventDefault();
        setIsResizing(true);
    };

    const handleMouseMove = (e: MouseEvent) => {
        if (!isResizing) return;

        // 计算新宽度，限制在最小和最大值之间
        let newWidth = e.clientX;
        if (newWidth < MIN_TREE_WIDTH) newWidth = MIN_TREE_WIDTH;
        if (newWidth > MAX_TREE_WIDTH) newWidth = MAX_TREE_WIDTH;

        setDirectoryTreeWidth(newWidth);
    };

    const handleMouseUp = () => {
        if (!isResizing) return;

        setIsResizing(false);

        // 保存宽度设置到localStorage
        if (typeof window !== 'undefined') {
            localStorage.setItem('directoryTreeWidth', directoryTreeWidth.toString());
        }
    };

    // 添加全局鼠标事件监听器
    useEffect(() => {
        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('mouseup', handleMouseUp);

        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isResizing, directoryTreeWidth]);

    /**存在目录时渲染函数*/
    function List(listFolder: any, listNote: any) {
        return (
            <div className="flex h-screen">
                {/* 左侧目录树 */}
                <div
                    className={`hidden sm:block transition-all duration-300 h-full border-r dark:border-divider dark:bg-default-100 overflow-hidden`}
                    style={{
                        width: showDirectoryTree ? `${directoryTreeWidth}px` : '0px',
                        minWidth: showDirectoryTree ? `${directoryTreeWidth}px` : '0px',
                        maxWidth: `${MAX_TREE_WIDTH}px`
                    }}
                >
                    {showDirectoryTree && (
                        <DirectoryTree
                            onSelectDirectory={handleSelectDirectory}
                            currentDirectoryId={search.get("path")}
                            onToggleVisibility={() => setShowDirectoryTree(false)}
                        />
                    )}
                </div>

                {/* 分隔条 */}
                {showDirectoryTree && (
                    <div
                        className="hidden sm:flex flex-col items-center justify-center w-1 bg-default-200 hover:bg-primary-300 cursor-col-resize h-full transition-colors duration-150 relative group"
                        onMouseDown={handleMouseDown}
                        style={{
                            cursor: isResizing ? 'col-resize' : 'default'
                        }}
                    >
                        {/* 拖动指示器 - 居中且更小 */}
                        <div className="absolute top-1/2 transform -translate-y-1/2 flex items-center justify-center h-14 w-1.5 bg-default-100 dark:bg-default-200 rounded-full group-hover:bg-primary-200 dark:group-hover:bg-primary-700 transition-colors">
                            <div className="flex flex-col items-center space-y-1">
                                <div className="w-px h-4 bg-default-400 group-hover:bg-primary-500"></div>
                                <div className="w-px h-4 bg-default-400 group-hover:bg-primary-500"></div>
                            </div>
                        </div>
                    </div>
                )}

                {/* 主内容区域 */}
                <div className="flex-grow overflow-auto bg-white dark:bg-default-100">
                    <div className="flex-col justify-center flex-grow items-start p-3 space-y-3">
                        {/* 面包屑导航和目录树开关按钮 */}
                        <div className="hidden sm:flex items-center w-full">
                            <div className="flex items-center">
                                {/* 目录树打开按钮 - 仅当目录树隐藏时显示 */}
                                {!showDirectoryTree && (
                                    <Button
                                        isIconOnly
                                        size="sm"
                                        variant="light"
                                        className="mr-2 flex items-center justify-center"
                                        onPress={() => setShowDirectoryTree(true)}
                                    >
                                        <BiChevronRight size={18} />
                                    </Button>
                                )}

                                <Breadcrumbs key={"boy"} variant={"light"} color={"foreground"} size={"md"}
                                    hideSeparator
                                    classNames={{
                                        list: "gap-3"
                                    }}
                                    itemClasses={{
                                        item: [
                                            "px-2 py-0.5 border-small border-default-400 rounded-small",
                                            "data-[current=true]:border-default-800 data-[current=true]:bg-foreground data-[current=true]:text-background transition-colors",
                                            "data-[disabled=true]:border-default-400 data-[disabled=true]:bg-default-100",
                                            "dark:text-white light:text-black dark:bg-black"
                                        ]
                                    }}
                                >
                                    {/* 目录树切换按钮 */}
                                    <Button
                                        isIconOnly
                                        size="sm"
                                        variant="light"
                                        className="mr-2 flex items-center justify-center"
                                        onPress={() => setShowDirectoryTree(!showDirectoryTree)}
                                    >
                                        {showDirectoryTree ? <BiChevronLeft size={18} /> : <BiChevronRight size={18} />}
                                    </Button>

                                    {/* 面包屑路径 */}
                                    {path.map((segment, index) => (
                                        <BreadcrumbItem
                                            onPress={() => {
                                                if (segment === "/") {
                                                    setPath(["/"])
                                                    setSearch("")
                                                    return
                                                }
                                                setSearch(`path=${segment}`)
                                            }}
                                            key={segment}
                                            startContent={segment === "/" ? <AiFillHome /> : <BiFolderOpen />}
                                        >
                                            <span className="max-w-[120px] truncate inline-block" title={segment === "/" ? "根目录" : (folderNameMap[segment] || segment)}>
                                                {segment === "/" ? "根目录" : (folderNameMap[segment] || segment)}
                                            </span>
                                        </BreadcrumbItem>
                                    ))}
                                </Breadcrumbs>
                            </div>
                        </div>

                        {/* 移动设备的目录导航 */}
                        <div className="sm:hidden w-full">
                            <Card className="w-full mb-3" shadow="sm">
                                <CardBody className="py-2">
                                    <Dropdown>
                                        <DropdownTrigger>
                                            <Button
                                                variant="light"
                                                endContent={<BiChevronDown />}
                                                className="w-full justify-between"
                                            >
                                                <div className="flex items-center">
                                                    {search.get("path") ? <BiFolderOpen className="mr-2" /> : <BiHomeAlt className="mr-2" />}
                                                    <span className="truncate">
                                                        {search.get("path")
                                                            ? folderNameMap[search.get("path") || ""] || "加载中..."
                                                            : "根目录"}
                                                    </span>
                                                </div>
                                            </Button>
                                        </DropdownTrigger>
                                        <DropdownMenu aria-label="目录导航" className="max-h-64 overflow-auto">
                                            <DropdownItem
                                                key="root"
                                                startContent={<BiHomeAlt />}
                                                onPress={() => handleSelectDirectory(null)}
                                                className={!search.get("path") ? "bg-primary-100/50 dark:bg-primary-800/30 text-primary" : ""}
                                            >
                                                根目录
                                            </DropdownItem>
                                            <DropdownItem isReadOnly className="text-primary">
                                                目录结构
                                            </DropdownItem>
                                            {/* 移除DirectoryTree，替换为简单的文件夹列表 */}
                                            {listFolder && listFolder.items && listFolder.items.map((folder: any) => (
                                                <DropdownItem
                                                    key={folder.id}
                                                    startContent={<BiFolderOpen className="text-primary" />}
                                                    onPress={() => {
                                                        handleSelectDirectory(folder.id);
                                                        // 关闭下拉菜单
                                                        document.body.click();
                                                    }}
                                                    className={search.get("path") === folder.id.toString() ?
                                                        "bg-primary-100/50 dark:bg-primary-800/30 text-primary" : ""}
                                                    textValue={folder.name}
                                                >
                                                    <span className="truncate">{folder.name}</span>
                                                </DropdownItem>
                                            ))}
                                        </DropdownMenu>
                                    </Dropdown>
                                </CardBody>
                            </Card>
                        </div>

                        {/* 目录渲染*/}
                        {
                            //加载中状态判断
                            isLoadingFolder ?
                                <Card shadow={"sm"} radius={"lg"}>
                                    <CardBody>
                                        <div className={"flex justify-center flex-grow items-center pb-4"}>
                                            <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                                                size={"sm"} />
                                        </div>
                                    </CardBody>
                                </Card> : (
                                    folderIfGrid == 'true' && cookie.load('folderIfGrid') != undefined ?
                                        <Card className="w-full" shadow={"sm"} radius={"lg"}>
                                            <CardHeader className="justify-between bg-white dark:bg-default-100">
                                                {createFolder()}
                                            </CardHeader>
                                            <CardBody className="px-3">
                                                {
                                                    listFolder.items.length === 0 ?
                                                        <div className={"flex justify-center flex-grow items-center pb-4"}>
                                                            <Code color="warning"> 暂无文件夹哦 🧐 </Code>
                                                        </div> :
                                                        <div className="gap-2 grid grid-cols-2 sm:grid-cols-6">
                                                            {listFolder.items.map(renderFolderGrid)}
                                                        </div>
                                                }
                                                {/* 分页控件 - 仅当总数大于每页数量时显示 */}
                                                {folderTotal > pageSize && (
                                                    <div className="flex justify-center mt-4">
                                                        <Button.Group>
                                                            <Button
                                                                disabled={folderCurrent === 1}
                                                                onClick={() => setFolderCurrent(folderCurrent - 1)}
                                                                color="primary"
                                                                variant="flat"
                                                            >
                                                                上一页
                                                            </Button>
                                                            <Button
                                                                disabled={folderCurrent * pageSize >= folderTotal}
                                                                onClick={() => setFolderCurrent(folderCurrent + 1)}
                                                                color="primary"
                                                                variant="flat"
                                                            >
                                                                下一页
                                                            </Button>
                                                        </Button.Group>
                                                    </div>
                                                )}
                                            </CardBody>
                                        </Card>
                                        :
                                        listFolder.items.length === 0 ?
                                            DontExitsFolder("暂无文件夹哦 🧐") :
                                            <Table
                                                title={"我的文件夹"}
                                                aria-label="我的所有文件夹."
                                                shadow={"sm"}/*阴影*/
                                                hideHeader={false}/*隐藏头部*/
                                                isStriped={false}/*条纹化*/
                                                topContent={
                                                    <div className={"flex justify-between items-center"}>
                                                        {createFolder()}
                                                    </div>
                                                }
                                                bottomContent={
                                                    folderTotal > pageSize ? (
                                                        <div className="flex justify-center">
                                                            <Button.Group>
                                                                <Button
                                                                    disabled={folderCurrent === 1}
                                                                    onClick={() => setFolderCurrent(folderCurrent - 1)}
                                                                    color="primary"
                                                                    variant="flat"
                                                                >
                                                                    上一页
                                                                </Button>
                                                                <Button
                                                                    disabled={folderCurrent * pageSize >= folderTotal}
                                                                    onClick={() => setFolderCurrent(folderCurrent + 1)}
                                                                    color="primary"
                                                                    variant="flat"
                                                                >
                                                                    下一页
                                                                </Button>
                                                            </Button.Group>
                                                        </div>
                                                    ) : null
                                                }
                                                onClick={() => {
                                                }}
                                                onRowAction={(key) => {
                                                    /*setPath(key) 我使用第二种方式*/
                                                    /*设置新的目录ID*/
                                                    // 查找对应的文件夹项
                                                    const folder = listFolder.items.find((item: any) => item.id.toString() === key.toString());
                                                    if (folder) {
                                                        // 保存文件夹名称
                                                        setFolderNameMap(prev => ({
                                                            ...prev,
                                                            [key]: folder.name
                                                        }));
                                                    }
                                                    setSearch(`path=${key}`)
                                                    /*const newPath = [...path, `${key}`];
                                                    setPath(newPath);*/
                                                    //更新加载中状态
                                                    setIsLoadingNote(true)
                                                    setIsLoadingFolder(true)
                                                }
                                                }/*获取key 这里是ID*/
                                                fullWidth={true}
                                            >
                                                <TableHeader>
                                                    <TableColumn align={"center"} key="num">
                                                        #
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="name">
                                                        目录名
                                                    </TableColumn>
                                                    <TableColumn className={`w-full`} align={"center"} key="description">
                                                        目录简介
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="createTime">
                                                        创建时间
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="status">
                                                        分享状态
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="actions">
                                                        操作
                                                    </TableColumn>
                                                </TableHeader>
                                                {/*设置内容*/}
                                                <TableBody
                                                    items={listFolder.items}
                                                    isLoading={isLoadingFolder}
                                                    loadingContent={<Spinner label="加载中..." />}
                                                >
                                                    {(item: any) => (
                                                        <TableRow key={item.id} className={"h-10"}>
                                                            {(columnKey) =>
                                                                <TableCell>{renderCell(item, columnKey, true)}</TableCell>
                                                            }
                                                        </TableRow>
                                                    )}
                                                </TableBody>
                                            </Table>
                                )
                        }

                        {/*笔记渲染*/}
                        {
                            //加载中状态判断
                            isLoadingNote ?
                                <Card shadow={"sm"} radius={"lg"}>
                                    <CardBody>
                                        <div className={"flex justify-center flex-grow items-center pb-4"}>
                                            <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                                                size={"sm"} />
                                        </div>
                                    </CardBody>
                                </Card> : (
                                    noteIfGrid == 'true' && cookie.load('noteIfGrid') != undefined ?
                                        /*新自定义列表*/
                                        <Card className="w-full" shadow={"sm"} radius={"lg"}>
                                            <CardHeader className="justify-between bg-white dark:bg-default-100">
                                                {createNote()}
                                            </CardHeader>
                                            <CardBody className="px-3">
                                                {
                                                    (inSearch ? findNote.items : listNote.items).length === 0 ?
                                                        <div className={"flex justify-center flex-grow items-center pb-4"}>
                                                            <Code
                                                                color="warning"> {inSearch ? "没搜到笔记哦 🥸" : "暂无笔记哦 🥸"} </Code>
                                                        </div> :
                                                        <div className="gap-2 grid grid-cols-2 sm:grid-cols-6">
                                                            {console.log("渲染的笔记列表项目:", inSearch ? findNote.items : listNote.items)}
                                                            {(inSearch ? findNote.items : listNote.items).map((item: any, index: number) => (
                                                                <div key={item.id}
                                                                    className="relative border-0 rounded-xl overflow-hidden shadow-0"
                                                                    onClick={(key) => {
                                                                        /*打开阅读界面*/
                                                                        router.push(`/note/${item.id}?collectionId=${search.get("path")}`);
                                                                    }}
                                                                >
                                                                    <div className="ps-3 pe-3 pt-3 pb-3 text-center">
                                                                        {/* 图标部分 - 设置固定高度确保对齐 */}
                                                                        <div className="flex items-center justify-center mb-3 h-16">
                                                                            {item.icon ? (
                                                                                <div className="w-16 h-16 rounded-md overflow-hidden flex items-center justify-center mx-auto">
                                                                                    <Image
                                                                                        src={item.icon}
                                                                                        alt={item.name}
                                                                                        className="w-full h-full object-cover"
                                                                                    />
                                                                                </div>
                                                                            ) : (
                                                                                <div className="w-16 h-16 flex items-center justify-center mx-auto">
                                                                                    <p className="text-5xl">{item.emoji || "📝"}</p>
                                                                                </div>
                                                                            )}
                                                                        </div>

                                                                        <h3 className="text-[13px] text-gray-600 mb-2 line-clamp-1 dark:text-white light:text-black ">{item.title}</h3>
                                                                        <p className="text-xs text-gray-500 mb-1">{item.updateTime || item.updatedAt || "未知"}</p>
                                                                        <Chip size="sm" color="secondary" variant="flat" className="mb-2">
                                                                            浏览: {item.viewCount || 0}
                                                                        </Chip>
                                                                        <div className={`flex justify-between`}>
                                                                            <Switch isSelected={item.isShared}
                                                                                color="secondary"
                                                                                size={"sm"}
                                                                                onValueChange={(isSelected) => {
                                                                                    setNoteId(item.id)
                                                                                    if (!isSelected) {
                                                                                        //选中 - 取消分享
                                                                                        if (item.shareId) {
                                                                                            cancelShare(item.shareId).then(() => {
                                                                                                ToastUtil("取消分享成功", "🎉", "success")
                                                                                                PubSub.publish("refreshNote", true);
                                                                                            }).catch(error => {
                                                                                                ToastUtil("取消分享失败", "❌", "error")
                                                                                                console.error("取消分享失败:", error);
                                                                                            });
                                                                                        }
                                                                                    } else {
                                                                                        //未选中 - 打开分享管理模态框
                                                                                        setShareNoteId(parseInt(item.id));
                                                                                        setIsOpenNoteShare(true);
                                                                                    }
                                                                                }} />
                                                                            <div className="relative flex justify-center items-end gap-2">
                                                                                <Dropdown backdrop={"transparent"}
                                                                                    className="bg-background border-1 border-default-200">
                                                                                    <DropdownTrigger>
                                                                                        <Button isIconOnly radius="full"
                                                                                            size="sm"
                                                                                            variant="light"
                                                                                            onClick={(e) => e.stopPropagation()}>
                                                                                            <BiDotsVerticalRounded
                                                                                                className="text-default-400" />
                                                                                        </Button>
                                                                                    </DropdownTrigger>
                                                                                    <DropdownMenu onAction={(key) => {
                                                                                        setDelData(key.toString())
                                                                                        onOpenDelNote()
                                                                                    }}
                                                                                    >
                                                                                        <DropdownItem color={"danger"}
                                                                                            key={item.id}
                                                                                            className="dark:text-white light:text-black"
                                                                                            startContent={
                                                                                                <DeleteIcon />}>删
                                                                                            除</DropdownItem>
                                                                                    </DropdownMenu>
                                                                                </Dropdown>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            ))}
                                                        </div>
                                                }
                                                {/* 分页控件 - 仅当总数大于每页数量时显示 */}
                                                {!inSearch && noteTotal > pageSize && (
                                                    <div className="flex justify-center mt-4">
                                                        <Button.Group>
                                                            <Button
                                                                disabled={noteCurrent === 1}
                                                                onClick={() => setNoteCurrent(noteCurrent - 1)}
                                                                color="secondary"
                                                                variant="flat"
                                                            >
                                                                上一页
                                                            </Button>
                                                            <Button
                                                                disabled={noteCurrent * pageSize >= noteTotal}
                                                                onClick={() => setNoteCurrent(noteCurrent + 1)}
                                                                color="secondary"
                                                                variant="flat"
                                                            >
                                                                下一页
                                                            </Button>
                                                        </Button.Group>
                                                    </div>
                                                )}
                                            </CardBody>
                                        </Card>
                                        :
                                        (inSearch ? findNote.items : listNote.items).length === 0 ?
                                            DontExitsNote(inSearch ? "没搜到笔记哦 🥸" : "暂无笔记哦 🥸") :
                                            <Table
                                                title={"我的云笔记"}
                                                aria-label="我的所有云笔记." color={"primary"}
                                                shadow={"sm"}/*阴影*/
                                                hideHeader={false}/*隐藏头部*/
                                                isStriped={false}/*条纹化*/
                                                topContent={
                                                    <div className={"flex justify-between items-center"}>
                                                        {createNote()}
                                                    </div>
                                                }
                                                bottomContent={
                                                    !inSearch && noteTotal > pageSize ? (
                                                        <div className="flex justify-center">
                                                            <Button.Group>
                                                                <Button
                                                                    disabled={noteCurrent === 1}
                                                                    onClick={() => setNoteCurrent(noteCurrent - 1)}
                                                                    color="secondary"
                                                                    variant="flat"
                                                                >
                                                                    上一页
                                                                </Button>
                                                                <Button
                                                                    disabled={noteCurrent * pageSize >= noteTotal}
                                                                    onClick={() => setNoteCurrent(noteCurrent + 1)}
                                                                    color="secondary"
                                                                    variant="flat"
                                                                >
                                                                    下一页
                                                                </Button>
                                                            </Button.Group>
                                                        </div>
                                                    ) : null
                                                }
                                                onRowAction={(key) => {
                                                    /*打开阅读界面*/
                                                    router.push(`/note/${key}?collectionId=${search.get("path")}`);
                                                }}
                                                fullWidth={true}
                                            >
                                                <TableHeader>
                                                    <TableColumn align={"center"} key="num">
                                                        #
                                                    </TableColumn>
                                                    <TableColumn className={`w-full`} align={"center"} key="title">
                                                        笔记名
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="updateTime">
                                                        修改时间
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="viewCount">
                                                        阅读次数
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="status">
                                                        分享状态
                                                    </TableColumn>
                                                    <TableColumn align={"center"} key="actions">
                                                        操作
                                                    </TableColumn>
                                                </TableHeader>
                                                {/*设置内容*/}
                                                <TableBody
                                                    items={inSearch ? findNote.items : listNote.items}
                                                    isLoading={isLoadingNote}
                                                    loadingContent={<Spinner label="加载中..." />}
                                                >
                                                    {/*渲染list*/}
                                                    {(item: any) => (
                                                        <TableRow key={item.id} className={"h-10"}>
                                                            {(columnKey) =>
                                                                <TableCell>{renderCell(item, columnKey, false)}</TableCell>
                                                            }
                                                        </TableRow>
                                                    )}
                                                </TableBody>
                                            </Table>
                                )
                        }

                        {/*编辑器*/}
                        {/* 删除这部分代码
                        <NoteEdit isOpen={isOpen} onOpenChange={onOpenChange} noteId={noteId}
                                  folderId={search.get("path")}/>
                        */}
                        {/*创建文件夹*/}
                        <CreateFolder isOpenFolder={isOpenFolder} onOpenChangeFolder={onOpenChangeFolder}
                            parentId={search.get("path")} />
                        {/*创建笔记*/}
                        {/* 删除这部分代码
                        <CreateNote isOpenNote={isOpenNote} onOpenChangeNote={onOpenChangeNote}
                                    folderId={search.get("path")}/>
                        */}
                        {/*删除笔记*/}
                        <DelNoteService isOpenDelNote={isOpenDelNote} onOpenChangeDelNote={onOpenChangeDelNote}
                            noteId={delData} />
                        {/*删除文件夹*/}
                        <DelFolderService isOpenDelFolder={isOpenDelFolder} onOpenChangeDelFolder={onOpenChangeDelFolder}
                            folderId={delData} />
                        {/*UpdateFolder*/}
                        <UpdateFolder isOpen={isOpenUpdateFolder} onOpenChange={onOpenChangeUpdateFolder} folderId={updateFolderId} />
                        {/*分享笔记模态框*/}
                        <NoteShareModal
                            noteId={shareNoteId}
                            isOpen={isOpenNoteShare}
                            onClose={() => setIsOpenNoteShare(false)}
                            onShareCreated={() => {
                                PubSub.publish("refreshNote", true);
                            }}
                            onShareCanceled={() => {
                                PubSub.publish("refreshNote", true);
                            }}
                        />
                    </div>
                </div>
            </div>
        )
    }

    /**新建笔记TabBar*/
    function createNote() {
        return (
            <>
                <Chip color="default" variant="light">我的笔记 📚</Chip>
                <Chip className={`ml-auto ps-4 me-4`} color="default" variant="faded" title={"排列方式"}
                    startContent={noteIfGrid == 'true' ? <AiOutlineBars size={18} /> :
                        <AiOutlineAppstore size={18} />}
                    onClick={(v) => {
                        if (noteIfGrid == 'true' && cookie.load('noteIfGrid') != undefined) {
                            cookie.remove('noteIfGrid')
                            setNoteIfGrid('false')
                        } else {
                            cookie.save('noteIfGrid', 'true', { expires: inFifteenMinutes, path: '/' })
                            setNoteIfGrid('true')
                        }
                    }}></Chip>
                <Button color="primary"
                    onClick={() => openCreate()}
                    startContent={<BiAddToQueue size={20} />}
                    className={'w-min'}>
                    新建笔记
                </Button>
            </>
        )
    }

    /**新建目录TabBar*/
    function createFolder() {
        return (
            <>
                <Chip color="default" variant="light">我的目录 📂</Chip>
                <Chip className={`ml-auto ps-4 me-4`} color="default" variant="faded" title={"排列方式"}
                    startContent={folderIfGrid == 'true' ? <AiOutlineBars size={18} /> :
                        <AiOutlineAppstore size={18} />}
                    onClick={(v) => {
                        if (folderIfGrid == 'true' && cookie.load('folderIfGrid') != undefined) {
                            cookie.remove('folderIfGrid')
                            setFolderIfGrid('false')
                        } else {
                            cookie.save('folderIfGrid', 'true', { expires: inFifteenMinutes, path: '/' })
                            setFolderIfGrid('true')
                        }
                    }}></Chip>
                <Button color="primary"
                    onClick={onOpenFolder}
                    startContent={<BiAddToQueue size={20} />}
                    className={'w-min'}>
                    新建目录
                </Button>
            </>
        )
    }

    /**不存在的目录时返回的组件函数*/
    function DontExitsFolder(message: string) {
        return (
            <div>
                <Card shadow={"sm"} radius={"lg"}>
                    <CardBody>
                        <div className={"flex justify-between items-center"}>
                            {createFolder()}
                        </div>
                        <div className={"flex justify-center flex-grow items-center pb-4 pt-4"}>
                            <Code color="warning"> {message} </Code>
                        </div>
                    </CardBody>
                </Card>
            </div>
        )
    }

    /**不存在的文件时返回的组件函数*/
    function DontExitsNote(message: string) {
        return (
            <div>
                <Card shadow={"sm"} radius={"lg"}>
                    <CardBody>
                        <div className={"flex justify-between items-center"}>
                            {createNote()}
                        </div>
                        <div className={"flex justify-center flex-grow items-center pb-4 pt-4"}>
                            <Code color="warning"> {message} </Code>
                        </div>
                    </CardBody>
                </Card>
            </div>
        )
    }

    /**获取部分路径*/
    function getPathParts(path: string) {
        return path.split("/").filter(part => part) //将路径分割为部分并过滤掉空白部分
    }

    /**规则化输出数据*/
    const renderCell = React.useCallback((List: any, columnKey: any, isFolder: boolean) => {
        const cellValue = List[columnKey]
        if (isFolder) {
            switch (columnKey) {
                case "num":
                    return (
                        // 优先显示icon，其次显示emoji，都没有才显示默认图标
                        List.icon ? (
                            <div className="w-10 h-10 aspect-square rounded-md overflow-hidden flex items-center justify-center">
                                <Image
                                    src={List.icon}
                                    alt={List.name}
                                    className="w-full h-full object-cover"
                                />
                            </div>
                        ) : (
                            <div className="w-10 h-10 aspect-square flex items-center justify-center">
                                <p className="text-2xl">{List.emoji || "📁"}</p>
                            </div>
                        )
                    )
                case "id":
                    return (
                        <Chip className={"capitalize"} color={"primary"} variant={"flat"}
                            size={"sm"}>&nbsp;{List.id}&nbsp;</Chip>
                    )
                case "createTime":
                    return (
                        <Chip color="primary" variant="dot" size={"sm"}>{List.createdAt || List.createTime || "未知"}</Chip>
                    )
                case "status":
                    return (
                        <Switch isSelected={false} color="default" size={"sm"} onValueChange={() => {
                            ToastUtil("不支持分享目录", "❎", "error")
                        }} />
                    )
                case "name":
                    return (
                        <h6 className={"w-[150px] line-clamp-1 overflow-hidden dark:text-white light:text-black "}>{List.name}</h6>
                    )
                case "description":
                    return (
                        <h6 className={"w-[250px] line-clamp-1 overflow-hidden dark:text-gray-400"}>
                            {List.description ? List.description : <span className="text-gray-400 text-xs">暂无描述</span>}
                        </h6>
                    )
                case "actions":
                    return (
                        <div className="relative flex justify-center items-end gap-2">
                            <Dropdown backdrop={"transparent"} className="bg-background border-1 border-default-200">
                                <DropdownTrigger>
                                    <Button isIconOnly radius="full" size="sm" variant="light">
                                        <BiDotsVerticalRounded className="text-default-400" />
                                    </Button>
                                </DropdownTrigger>
                                <DropdownMenu onAction={(key) => {
                                    if (key === "edit") {
                                        // 点击编辑按钮
                                        setUpdateFolderId(List.id.toString());
                                        onOpenUpdateFolder();
                                    } else {
                                        // 点击删除按钮
                                        setDelData(key.toString());
                                        onOpenDelFolder();
                                    }
                                }}>
                                    <DropdownItem
                                        key="edit"
                                        className={`dark:text-white light:text-black `}
                                        startContent={<BiEdit className="text-blue-500" />}
                                    >
                                        编辑
                                    </DropdownItem>
                                    <DropdownItem
                                        color={"danger"}
                                        className={`dark:text-white light:text-black `}
                                        key={List.id}
                                        startContent={<DeleteIcon />}
                                    >
                                        删除
                                    </DropdownItem>
                                </DropdownMenu>
                            </Dropdown>
                        </div>
                    )
                default:
                    return cellValue
            }
        } else {
            switch (columnKey) {
                case "num":
                    return (
                        // 优先显示icon，其次显示emoji，都没有才显示默认图标
                        List.icon ? (
                            <div className="w-10 h-10 aspect-square rounded-md overflow-hidden flex items-center justify-center">
                                <Image
                                    src={List.icon}
                                    alt={List.name}
                                    className="w-full h-full object-cover"
                                />
                            </div>
                        ) : (
                            <div className="w-10 h-10 aspect-square flex items-center justify-center">
                                <p className="text-2xl">{List.emoji || "📁"}</p>
                            </div>
                        )
                    )
                case "id":
                    return (
                        <Chip className={"capitalize"} variant={"flat"} size={"sm"}
                            color={"secondary"}>&nbsp;{List.id}&nbsp;</Chip>
                    )
                case "createTime":
                    return (
                        <Chip color="secondary" variant="dot" size={"sm"}>{List.createdAt || List.createTime || "未知"}</Chip>
                    )
                case "updateTime":
                    return (
                        <Chip color="secondary" variant="dot" size={"sm"}>{List.updatedAt || List.updateTime || "未知"}</Chip>
                    )
                case "viewCount":
                    return (
                        <Chip color="secondary" variant="flat" size={"sm"}>{List.viewCount || 0}</Chip>
                    )
                case "status":
                    return (
                        <Switch isSelected={List.isShared} color="secondary" size={"sm"}
                            onValueChange={(isSelected) => {
                                setNoteId(List.id)
                                if (!isSelected) {
                                    //选中 - 取消分享
                                    if (List.shareId) {
                                        cancelShare(List.shareId).then(() => {
                                            ToastUtil("取消分享成功", "🎉", "success")
                                            PubSub.publish("refreshNote", true);
                                        }).catch(error => {
                                            ToastUtil("取消分享失败", "❌", "error")
                                            console.error("取消分享失败:", error);
                                        });
                                    }
                                } else {
                                    //未选中 - 打开分享管理模态框
                                    setShareNoteId(parseInt(List.id));
                                    setIsOpenNoteShare(true);
                                }
                            }} />
                    )
                case "title":
                    return (
                        <h6 className={"w-[250px] line-clamp-1 overflow-hidden dark:text-white light:text-black "}>{List.title}</h6>
                    )
                case "actions":
                    return (
                        <NoteListActions
                            noteId={List.id}
                            collectionId={search.get("path")}
                            onDeleteSuccess={() => listNote.reload()}
                        />
                    )
                default:
                    return cellValue
            }
        }
    }, [onOpenDelFolder, onOpenDelNote, onOpenUpdateFolder, router])

    // 修改网格视图渲染，只居中图标和表情
    const renderFolderGrid = (item: any, index: bigint) => (
        <div key={index}
            className="relative border-0 rounded-xl overflow-hidden shadow-0"
            onClick={(key) => {
                // 保存文件夹名称
                setFolderNameMap(prev => ({
                    ...prev,
                    [item.id]: item.name
                }));
                setSearch(`path=${item.id}`);
                setIsLoadingNote(true);
                setIsLoadingFolder(true);
            }}
        >
            <div className="ps-3 pe-3 pt-3 pb-3 text-center">
                {/* 图标部分 - 设置固定高度确保对齐 */}
                <div className="flex items-center justify-center mb-3 h-16">
                    {item.icon ? (
                        <div className="w-16 h-16 rounded-md overflow-hidden flex items-center justify-center mx-auto">
                            <Image
                                src={item.icon}
                                alt={item.name}
                                className="w-full h-full object-cover"
                            />
                        </div>
                    ) : (
                        <div className="w-16 h-16 flex items-center justify-center mx-auto">
                            <p className="text-5xl">{item.emoji || "📁"}</p>
                        </div>
                    )}
                </div>

                <h3 className="text-[13px] font-medium text-gray-600 mb-1 dark:text-white light:text-black line-clamp-1">{item.name}</h3>
                <h3 className="text-xs text-gray-500 mb-2 h-8 line-clamp-2">
                    {item.description || "---"}
                </h3>
                <p className="text-xs text-gray-500 mb-1">{item.createdAt || item.createTime || "未知"}</p>
                <div className={`flex justify-between`}>
                    <Switch isSelected={item.isShared}
                        color="secondary"
                        size={"sm"}
                        onValueChange={(isSelected) => {
                            setNoteId(item.id)
                            if (!isSelected) {
                                //选中 - 取消分享
                                if (item.shareId) {
                                    cancelShare(item.shareId).then(() => {
                                        ToastUtil("取消分享成功", "🎉", "success")
                                        PubSub.publish("refreshNote", true);
                                    }).catch(error => {
                                        ToastUtil("取消分享失败", "❌", "error")
                                        console.error("取消分享失败:", error);
                                    });
                                }
                            } else {
                                //未选中 - 打开分享管理模态框
                                setShareNoteId(parseInt(item.id));
                                setIsOpenNoteShare(true);
                            }
                        }} />
                    <div className="relative flex justify-center items-end gap-2">
                        <Dropdown backdrop={"transparent"}
                            className="bg-background border-1 border-default-200">
                            <DropdownTrigger>
                                <Button isIconOnly radius="full"
                                    size="sm"
                                    variant="light"
                                    onClick={(e) => e.stopPropagation()}>
                                    <BiDotsVerticalRounded
                                        className="text-default-400" />
                                </Button>
                            </DropdownTrigger>
                            <DropdownMenu onAction={(key) => {
                                if (key === "edit") {
                                    // 点击编辑按钮
                                    setUpdateFolderId(item.id.toString());
                                    onOpenUpdateFolder();
                                } else {
                                    // 点击删除按钮
                                    setDelData(key.toString());
                                    onOpenDelFolder();
                                }
                            }}>
                                <DropdownItem
                                    key="edit"
                                    className={`dark:text-white light:text-black`}
                                    startContent={<BiEdit className="text-blue-500" />}
                                >
                                    编辑
                                </DropdownItem>
                                <DropdownItem
                                    color={"danger"}
                                    className={`dark:text-white light:text-black`}
                                    key={item.id}
                                    startContent={<DeleteIcon />}
                                >
                                    删除
                                </DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </div>
                </div>
            </div>
        </div>
    );

    //判断是否加载完再返回

    /**等挂在之后再渲染 */
    const [mounted, setMounted] = useState(false)
    useEffect(() => {
        //组件挂载时执行一次Set的操作
        setMounted(true)
    }, [])

    if (!mounted) return null

    // 修改打开编辑器的函数，将其替换为导航到新页面
    function openEditor(noteIds: any) {
        setNoteId(noteIds);
        // 不再打开Modal，而是导航到编辑页面
        router.push(`/note/${noteIds}?collectionId=${search.get("path")}`);
    }

    // 修改打开创建笔记的函数
    function openCreate() {
        // 导航到新建页面
        router.push(`/note/new?collectionId=${search.get("path")}`);
    }

    /**本Page（页）返回的DOM元素*/
    return List(listFolder, listNote)
}